package com.example.myapplication.Sign;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alipay.sdk.app.OpenAuthTask;
import com.example.myapplication.MainActivity;
import com.example.myapplication.R;
import com.example.myapplication.db.DBManager;
import com.example.myapplication.db.DataManager;
import com.example.myapplication.db.domain.UserBean;

import java.util.HashMap;
import java.util.Map;


public class loginPage extends AppCompatActivity {

//    返回按键
    private ImageView login_back;
//    手机号
    private EditText phoneNum;
//    密码
    private EditText password;
//    忘记密码选项
    private TextView forgetPassword;
//    注册账号选项
    private TextView registerAccount;
//    登录按钮
    private Button login_btn;
//    支付宝登录
    private ImageView alipay;

    private  OpenAuthTask.Callback callback =  new  OpenAuthTask.Callback() {
        @Override
        public void onResult(int i, String s, Bundle bundle) {
            if  (i == OpenAuthTask.OK) {
            /* 数据样例
                "app_id" = 2088432687422011;
                "auth_code" = 41f084c3ab4b4be6b6dd8d25dac1YF46;
                "result_code" = SUCCESS;
                "scope" = auth_user;
                "state" = XXXX（自定义 base64 编码）;
            */
                String appId = bundle.getString("app_id");

                // 执行原有处理逻辑
                UserBean bean = DBManager.findUserByAlipayCode(appId);
                if (bean != null){
                    try {
                        DataManager.isLogin = true;
                        DataManager.userId = bean.getId();
                        DataManager.phone = bean.getPhone();
                        DataManager.alipayCode = appId;
                        Toast.makeText(loginPage.this, "登录成功", Toast.LENGTH_LONG).show();
                        startActivity(new Intent(loginPage.this, MainActivity.class));
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else {
                    DataManager.isLogin = false;
                    DataManager.toBeBind = true;
                    DataManager.alipayCode = appId;
                    Toast.makeText(loginPage.this, "未绑定账号，请登录或注册进行绑定", Toast.LENGTH_LONG).show();
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_page);


        // 获取到xml中相应对象
        phoneNum = findViewById(R.id.login_phoneNumber);
        password = findViewById(R.id.login_password);
        forgetPassword = findViewById(R.id.forgetPassword);
        registerAccount = findViewById(R.id.registerAccount);
        login_btn = findViewById(R.id.login_btn);
        alipay = findViewById(R.id.icon_alipay);
        login_back = findViewById(R.id.login_back_btn);

        // 跳转到注册页面
        registerAccount.setOnClickListener(view -> {
            Intent intent = new Intent(loginPage.this,registerPage.class);
            startActivity(intent);
        });

        // 跳转到改密码的界面
        forgetPassword.setOnClickListener(view -> {
            Intent intent = new Intent(loginPage.this, forgetPage.class);
            startActivity(intent);
        });

        //  登录界面返回上一个界面
        login_back.setOnClickListener(view -> loginPage.this.finish());

        //  用户登录
        login_btn.setOnClickListener(v -> {
            String phone = "", pwd = "";
            try {
                phone = phoneNum.getText().toString().trim();
                pwd = AESCrypt.encrypt(password.getText().toString());
            }catch (Exception e){
                e.printStackTrace();
            }
            UserBean bean = DBManager.findUserByPhoneAndPassword(phone, pwd);
            if(bean != null){
                DataManager.isLogin = true;
                DataManager.userId = bean.getId();
                DataManager.phone = bean.getPhone();
                if (DataManager.toBeBind){
                    Toast.makeText(loginPage.this, "绑定成功", Toast.LENGTH_SHORT).show();
                    DBManager.updateAlipayCode(bean.getPhone(), DataManager.alipayCode);

                    //清除绑定状态
                    DataManager.toBeBind = false;
                }else {
                    Toast.makeText(loginPage.this, "登录成功", Toast.LENGTH_SHORT).show();
                }
                Intent intent = new Intent(loginPage.this, MainActivity.class);
                startActivity(intent);
            }else {
                DataManager.isLogin = false;
                Toast.makeText(loginPage.this, "手机号或密码错误", Toast.LENGTH_LONG).show();
            }
        });

        // 支付宝授权登录
        alipay.setOnClickListener(v -> {
            // 商家对接业务所约定的参数
            Map<String, String> bizParams =  new HashMap<>();
            bizParams.put( "url" ,  "authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id=2021003184633047&scope=auth_user&state=XXXXXXX" );   // key为URL，value是上文的URL值
            // 授权完成后回跳的scheme
            // 需与@{link com.alipay.sdk.app.AlipayResultActivity}的配置保持一致
            String scheme =  "authweb.alipay.com/auth?auth_type=PURE_OAUTH_SDK&app_id=2021003184633047&scope=auth_user&state=XXXXXXX" ;
            final OpenAuthTask task = new OpenAuthTask(loginPage.this);
            task.execute(
                    scheme, // Intent Scheme
                    OpenAuthTask.BizType.AccountAuth, // 业务类型
                    bizParams,
                    callback, // 业务结果回调
                    false); // 是否需要在用户未安装支付宝 App 时，使用 H5 中间页中转
        });
    }
}